from django.db.models.signals import post_delete, post_save

class CachedQuerySetManager:
	"""
	Manages a list of querysets that are automatically updated
	whenever an object is added to or deleted from one of them.
	"""
	def __init__(self):
		self._querysets = {}
	
	def __getitem__(self, key):
		return self._querysets[key]["queryset"]
	
	def __len__(self):
		return len(self._querysets)
	
	def add(self, model, manager = "_default_manager"):
		self._querysets[model] = {
			"queryset" : getattr(model, manager).all(),
			"manager" : manager,
		}
		post_delete.connect(self.update, sender = model)
		post_save.connect(self.update, sender = model)
	
	def keys(self):
		return self._querysets.keys()
	
	def remove(self, model):
		post_delete.disconnect(self.update, sender = model)
		post_save.disconnect(self.update, sender = model)
		del self._querysets[model]
	
	def update(self, sender, **kwargs):
		self._querysets[sender]["queryset"] = \
			getattr(sender, self._querysets[sender]["manager"]).all()

cached_querysets = CachedQuerySetManager()
